package com.zxw.mallafter.service.impl;

import com.zxw.mallafter.service.UploadFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class UploadFileSrviceimpl implements UploadFileService {
//文件上传路径
  @Value("${upload.location}")
    private String uploadFileLocation;
  //文件上传服务器前缀
  @Value("${upload.server.prefix}")
  private String uploadFilePrefix;
    @Override
    public String uploadAvatar(MultipartFile file) {
        //获取文件源名称
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成新的文件名
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        fileName+=suffixName;
        //文件上传路径
        File filePath = new File(uploadFileLocation + "/images/avatar/");
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try{
            File dest =new File(filePath.getCanonicalPath()+"/"+fileName);
            //将整个文件上传到指定的路径
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
        }

        return uploadFilePrefix+"images/avatar/"+fileName;
    }

}
